package main

import (
	"flag"
	"fmt"
	"net/smtp"
	"strings"
)

/*
send_mail 用法：
./send_mail -to=975806566@qq.com
*/

func SendToMail(user string, password string, host string, to string, subject string, body string, mailtype string) error {
	hp := strings.Split(host, ":")
	auth := smtp.PlainAuth("", user, password, hp[0])
	var content_type string
	if mailtype == "html" {
		content_type = "Content-Type: text/" + mailtype + "; charset=UTF-8"
	} else {
		content_type = "Content-Type: text/plain" + "; charset=UTF-8"
	}

	//msg := []byte("To: " + to + "\r\nFrom: <" + user + ">\r\nSubject: " + "\r\n" + content_type + "\r\n\r\n" + body)
	msg := []byte("To: " + to + "\r\nFrom: " + user + "<" + user + ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
	send_to := strings.Split(to, ";")
	err := smtp.SendMail(host, auth, user, send_to, msg)
	return err
}

const (
	DEFAULT_USER     = "975806566@qq.com"
	DEFAULT_PASSWORD = "xgtxvaujreijbbbb"
	DEFAULT_HOST     = "smtp.qq.com:25"
	DEFAULT_SUBJECT  = "IM_SERVER 监控邮件"
	DEFAULT_TO       = "527554192@qq.com"
	DEFAULT_CONTENT  = `
<html>
	<body>
		this is im_server monitor mail
	</body>
</html>
	`
)

func main() {

	user := flag.String("user", DEFAULT_USER, "发送消息的邮箱号码")
	password := flag.String("password", DEFAULT_PASSWORD, "发送邮件的帐号密码")
	host := flag.String("host", DEFAULT_HOST, "邮箱的host")
	subject := flag.String("subject", DEFAULT_SUBJECT, "邮件的标题")
	body := flag.String("body", DEFAULT_CONTENT, "邮件内容")

	to := flag.String("to", DEFAULT_TO, "邮件的接收者")
	flag.Parse()

	err := SendToMail(*user, *password, *host, *to, *subject, *body, "html")

	if err != nil {
		fmt.Println("send mail err", err)
	} else {
		fmt.Println("success")
	}
}
